<?php

namespace app\home\controller;

// 引入tp基础控制器
use think\Controller;

// 引入数据库的操作类
use think\Db;

// 引入视图类
use think\View;

// 引入客户来源模型
use app\common\model\Business\Source;

class Index extends Controller
{
    // 客户模型
    protected $BusinessModel = null;

    // 构造函数
    public function __construct()
    {
        // 手动继承父级的构造函数
        parent::__construct();

        // 加载模型
        $this->BusinessModel = model('Business.Business');
    }

    // 首页
    public function index()
    {
        $SubjectModel = model('Subject.Subject');

        $CategoryModel = model('Subject.Category');

        $TopList = $SubjectModel->OrderRaw("LPAD(LOWER(likes),10,0) DESC")->limit(8)->select();

        /* 
            1、查询所有的分类
            2、通过分类id查询当前分类下的所有课程
        */
        $CateData = $CategoryModel->order('weight DESC')->select();

        $CateList = [];

        foreach ($CateData as $item) {
            $SubjectList = $SubjectModel->where(['cateid' => $item['id']])->limit(6)->select();

            $CateList[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'subject' => $SubjectList
            ];
        }

        $data = [
            'TopList' => $TopList,
            'CateList' => $CateList
        ];

        return $this->fetch('', $data);
    }

    // 注册
    public function register()
    {
        // 13023568956

        // 判断是否有POST数据过来
        // request => 请求对象 负责接收
        if ($this->request->isPost()) {
            /* 
                input 助手函数 input('post.name')
                request 请求对象 => request() 助手函数

                mobile ? mobile : 1

                param => GET POST PUT

                request()->post()
             */
            $mobile = request()->post('mobile', '', 'trim');

            $password = $this->request->param('password', '', 'trim');

            $repass = $this->request->param('repass', '', 'trim');

            if (empty($password)) {
                $this->error('密码必填');
            }

            // 确认密码与密码不一致时给提示
            if ($password != $repass) {
                /* 
                    操作错误跳转的快捷方法
                    error = [
                        提示信息
                        跳转地址
                        返回数据
                        等待跳转时间
                    ]

                    success => 操作成功跳转的快捷方法
                */
                $this->error('密码与确认密码不一致');
            }



            // 查询客户来源表的云课堂id
            // SELECT id FROM `table` WHERE `name` = '云课堂'
            // $sourceid = Db::name('business_source')->where('name','云课堂')->fetchSql()->value('id');
            // getLastSql => 调试执行的sql语句 fetchSql => 返回当前的查询SQL而不执行
            // echo Db::getLastSql();
            // exit;
            // halt($sourceid);

            // $SourceModel = new Source();

            // $sourceid = $SourceModel->where(['name' => '云课堂'])->value('id');

            // echo $SourceModel::getLastSql();
            // exit;

            // model => 助手函数

            // 获取来源id
            $sourceid = model('Business.Source')->where(['name' => '云课堂'])->value('id');

            // 密码盐
            $salt = build_ranstr();

            // 进行加密
            $password = md5($password . $salt);

            // 封装数据
            $data = [
                'mobile' => $mobile,
                'password' => $password,
                'salt' => $salt,
                'invitecode' => build_ranstr(),
                'sourceid' => $sourceid
            ];

            // 验证数据并且插入数据库里
            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if ($result === FALSE) {
                $this->error($this->BusinessModel->getError());
            } else {
                $this->success('注册成功', url('home/index/login'));
            }
        }

        return $this->fetch();
    }

    // 登录
    public function login()
    {
        if ($this->request->isPost()) {
            // 接收参数 -> 通过手机号查询数据库是否存在 find(查询单条数据) -> 判断密码是否正确 -> 存储登录信息 cookie -> 跳转首页 

            $params = $this->request->param();

            if (empty($params['mobile']) || empty($params['password'])) {
                $this->error('手机号或者密码不能为空');
            }

            // 通过手机号查询数据表里面有没有这个用户
            $Business = $this->BusinessModel->where(['mobile' => $params['mobile']])->find();

            if (!$Business) {
                $this->error('用户不存在');
            }

            // 判断密码是否错误就提示
            $password = md5($params['password'] . $Business['salt']);

            if ($password != $Business['password']) {
                $this->error('密码错误');
            }

            // 能到这步说明登录成功了，需要存储登录信息
            $data = [
                'id' => $Business['id'],
                'nickname' => $Business['nickname'],
                'mobile' => $Business['mobile'],
                'avatar' => $Business['avatar'],
                'auth' => $Business['auth']
            ];

            cookie('LoginAuth', $data);

            $this->success('登录成功', url('home/business/index'));
        }
        return $this->fetch();
    }

    // 退出登录
    public function logout()
    {
        cookie('LoginAuth', null);
        $this->success('退出成功', url('home/index/login'));
    }

    // 联系我们
    public function contact()
    {
        $page = model('Category')->where(['name' => '云课堂'])->find();

        $this->assign([
            'page' => $page
        ]);

        return $this->fetch();
    }
}
